<template>
  <vx-card class="pt-5" full>
    <div class="userSearchTop">
      <div class="userSearch">
        <vs-input
          label="真实名称"
          size="small"
          icon="icon-search"
          icon-pack="feather"
          icon-after="true"
          class="inputx no-icon-border"
          v-model="searchList.realname"
          @blur="filterUser()"
        />
      </div>
      <vs-button
        color="primary"
        icon="icon-plus"
        icon-pack="feather"
        @click="handleAdd"
        size="small"
      >新增</vs-button>
    </div>
    <vx-table
      :data="tableData"
      :total="recordsTotal"
      :pageSize="pageSize"
      @current-change="currentChange"
      class="mt-4"
    >
      <el-table-column prop="realname" label="真实姓名" sortable width="200"></el-table-column>
      <el-table-column prop="username" label="用户名称" width="200"></el-table-column>
      <el-table-column prop="mobile" label="联系方式" width="250"></el-table-column>
      <el-table-column prop="status" width="100" label="状态">
        <template slot-scope="scope" align="center">
          <span v-if="scope.row.status == 1" style="color:RGB(115,206,126)">启用</span>
          <span v-else style="color:red">未启用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <feather-icon
            title="编辑"
            icon="EditIcon"
            :svgClasses="['stoke-current text-primary w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleEdit(scope.$index, scope.row)"
          />
          <feather-icon
            title="停用"
            v-if="scope.row.status ==1"
            icon="LockIcon"
            :svgClasses="['stoke-current text-success w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleSwitch(scope.$index, scope.row)"
          />
          <feather-icon
            v-else
            title="启用"
            icon="LockIcon"
            :svgClasses="['stoke-current text-warning w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleSwitch(scope.$index, scope.row)"
          />
          <feather-icon
            title="修改密码"
            icon="UserIcon"
            :svgClasses="['stoke-current w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleEditPassword(scope.$index, scope.row)"
          />
          <feather-icon
            title="删除"
            icon="Trash2Icon"
            :svgClasses="['stoke-current text-danger w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleDelete(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </vx-table>
    <!--新增-编辑 模态框开始 -->
    <vx-popup
      classContent="popup-example"
      :title="popTitle"
      :active.sync="popupActivoAdd"
      :isValid="handleIsValidate"
      @confirmPopup="addUser"
      @cancelPopup="popupActivoAdd = false;"
    >
      <div class="addPopcontent">
        <div class="pr-1">
          <vs-input
            label="登录名称："
            class="inputx mt-2 red"
            v-model="popList.username"
            name="登录名"
            data-vv-validate-on="input|blur"
            v-validate="'required|min:3'"
            :disabled="isEditor"
          />
          <span
            class="text-danger text-sm pl-1"
            v-show="errorBags.has('登录名')"
          >{{ errorBags.first('登录名')}}</span>
          <vs-input
            label="手机号码："
            class="inputx mt-2"
            v-model="popList.telephone"
            name="电话"
            data-vv-validate-on="input|blur"
            v-validate="'phone'"
          />
          <span
            class="text-danger text-sm pl-1"
            v-show="errorBags.has('电话')"
          >{{errorBags.first('电话')}}</span>
          <vs-input
            label="邮箱地址："
            class="inputx my-2"
            v-model="popList.mail"
            name="邮箱"
            data-vv-validate-on="input|blur"
            v-validate="'email'"
          />
          <span
            class="text-danger text-sm pl-1 mb-3 email"
            v-show="errorBags.has('邮箱')"
          >{{ errorBags.first('邮箱')}}</span>
              <span style="color:red">*</span>
          <div class="el-upload-list el-upload-list--picture-card mb-2 ml-1 mt-3" v-show="hideShow">
            <div class="el-upload-list__item is-success">
              <img class="flex-img__image" :src="file" width="100" height="100" />
              <label class="el-upload-list__item-status-label">
                <i class="el-icon-upload-success el-icon-check"></i>
              </label>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-delete">
                  <i class="el-icon-delete" @click.stop="handleRemove()"></i>
                </span>
              </span>
            </div>
          </div>
          <el-upload
            class="image-uploader mb-2 ml-1 mt-3"
            style="display:inline-block"
            list-type="picture-card"
            :action="uploadUrl"
            :show-file-list="false"
            accept="image/jpeg, image/jpg, image/png"
            :on-success="imageUploadSuccess"
            v-show="!hideShow"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div>
            <span style="color:red">*</span>默认密码为：12345678
          </div>
        </div>
        <div class="pl-1">
          <vs-input
            label="真实姓名:"
            class="inputx mt-2 red"
            v-model="popList.realname"
            name="真实姓名"
            data-vv-validate-on="input|blur"
            v-validate="'required'"
          />
          <span
            class="text-danger text-sm pl-1"
            v-show="errorBags.has('真实姓名')"
          >{{ errorBags.first('真实姓名')}}</span>
          <vs-input
            label="联系电话："
            name="移动电话"
            class="inputx mt-2 red"
            v-model="popList.mobile"
            data-vv-validate-on="input|blur"
            v-validate="'required|mobile'"
          />
          <span
            class="text-danger text-sm pl-1"
            v-show="errorBags.has('移动电话')"
          >{{ errorBags.first('移动电话')}}</span>
          <vs-input label="备注：" class="inputx my-2" v-model="popList.remark" />
          <span style="color:red">*</span>
          <span class="text-sm pl-2" style="margin-left:-4px">所属部门：</span>
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入"
            v-model="checkedDepartName"
            style="width:210px"
          ></el-input>
          <el-button class="chooseBtn" v-if="chooseDepart" slot="append" @click="switchDepart">选择</el-button>
          <el-button class="closeBtn" v-else slot="append" @click="switchDepart">关闭</el-button>

          <!-- <el-input v-model="checkedDepartName" readonly="readonly" class="ml-1">
            <el-button class="chooseBtn" v-if="chooseDepart" slot="append" @click="switchDepart">选择</el-button>
            <el-button class="closeBtn" v-else slot="append" @click="switchDepart">关闭</el-button>
          </el-input>-->
        </div>
      </div>
      <!-- 所属部门 -->
      <div class="vx-card departContainer" v-show="!chooseDepart">
        <h4 class="pl-3">部门选择</h4>
        <VuePerfectScrollbar class="mt-5 scroll-area">
          <tree-component
            ref="tree"
            node-key="id"
            :data="treeData"
            @check="getCheckedKeys"
            :render-content="renderContent"
            show-checkbox
            default-expand-all
          ></tree-component>
        </VuePerfectScrollbar>
      </div>
    </vx-popup>
    <!-- 新增-编辑 模态框结束 -->
    <!--设置密码模态框开始 -->
    <vx-popup
      classContent="popup-example"
      title="修改密码"
      width="400px"
      :active.sync="popupActivoPassword"
      :isValid="handleEditorPassword"
      @confirmPopup="confirmPassword"
      @cancelPopup="closeConfirmPassword"
      class="editPassword"
    >
      <vs-input
        type="password"
        label="原密码："
        class="inputx mt-2"
        name="原密码"
        v-model="popPasswordlist.oldPassword"
        data-vv-validate-on="input|blur"
        v-validate="'required|min:6'"
      />
      <span class="text-danger text-sm" v-show="errorBags.has('原密码')">{{ errorBags.first('原密码')}}</span>
      <vs-input
        type="password"
        label="新密码："
        name="新密码"
        class="inputx mt-2"
        data-vv-validate-on="input|blur"
        v-model="popPasswordlist.newPassword"
        v-validate="'required|min:6'"
      />
      <span class="text-danger text-sm" v-show="errorBags.has('新密码')">{{ errorBags.first('新密码')}}</span>
      <vs-input
        type="password"
        label="新密码确认："
        name="新密码确认"
        class="inputx mt-2"
        v-model="popPasswordlist.confirmNewPassword"
        v-validate="'required|min:6'"
        data-vv-validate-on="input|blur"
      />
      <span
        class="text-danger text-sm"
        v-show="errorBags.has('新密码确认')"
      >{{ errorBags.first('新密码确认')}}</span>
    </vx-popup>
    <!-- 设置密码模态框结束 -->
    <!--删除模态框开始 -->
    <vx-popup
      classContent="popup-example"
      title="删除"
      :active.sync="popupActivoDel"
      :isValid="true"
      width="400px"
      @confirmPopup="delData"
      @cancelPopup="popupActivoDel = false"
    >
      <span>确定删除这条数据吗？</span>
    </vx-popup>
    <!-- 删除模态框结束 -->
  </vx-card>
</template>
<script>
import VuePerfectScrollbar from "vue-perfect-scrollbar";
import TreeComponent from "@/components/model-tree/ModelTree.vue";
import base from "@/api/base"; // 导入接口域名列表
import md5 from "js-md5";
export default {
  props: ["image", "clearList"],
  data() {
    return {
      uploadUrl: base.accessUPLOADURL, //图片上传网址
      file: "",
      treeData: [],
      popTitle: "新增",
      searchList: {
        realname: "",
      },
      selectRowId: "",
      tableData: [],
      popList: {
        realname: "",
        username: "",
        telephone: "",
        mail: "",
        remark: "",
        sysDeptIds: [],
        mobile: "",
        icon: "",
      },
      checkedDepartName: "",
      popPasswordlist: {
        oldPassword: "",
        newPassword: "",
        confirmNewPassword: "",
      },
      userStatus: [
        { value: 0, text: "启用" },
        { value: 1, text: "未启用" },
      ],
      popupActivoAdd: false,
      popupActivoPassword: false,
      popupActivoDel: false,
      chooseDepart: true,
      isEditor: false,
      recordsTotal: 0,
      currentPage: 1,
      pageSize: 10,
    };
  },
  methods: {
    //显示上传图片
    imageUploadSuccess(res, file) {
      console.log(res);
      console.log(file, "////");
      this.file = URL.createObjectURL(file.raw);
      let obj = {
        id: "",
        fileSuffix: "",
        fileSizeType: "",
        originalFileName: "",
      };
      // this.iconUrl = res.data.successFiles[0].filePath
      let arr = [];
      Object.keys(obj).forEach((v) => {
        console.log(res.data.successFiles[0]);
        obj[v] = res.data.successFiles[0][v];
        obj.fileId = res.data.successFiles[0].id;
      });
      arr.push(obj);
      this.popList.icon = arr;
      console.log(this.popList.icon);
    },
    //删除图片
    handleRemove() {
      this.file = "";
      this.popList.icon = [];
    },
    //树名称显示
    renderContent(h, { node }) {
      let iconSkin;
      if (node.data.type == 5) {
        iconSkin = "icon-department";
      } else if (node.data.type == 3) {
        iconSkin = "icon-center";
      } else if (node.data.type == 4) {
        iconSkin = "icon-site";
      } else {
        iconSkin = "icon-group";
      }
      return (
        <span class="custom-tree-node flex items-center">
          <i class={`othericon ${iconSkin}`} />
          <span style="margin-left:5px;">{node.data.name}</span>
        </span>
      );
    },
    //获取部门树
    getDepartData() {
      this.$api.accessControl
        .departmentTree()
        .then((res) => {
          this.treeData = res.data.data;
          this.addDisabled(this.treeData);
        })
        .catch();
    },
    addDisabled(data){
      let arr = []
      data.forEach((item,index)=>{
        if(item.type == '4' && !item.children)
        arr.push(index)
      })
      for(let i = arr.length-1;i>=0;i--){
        data.splice(arr[i],1)
      }
      data.forEach(item=>{
        if(item.children)
        this.addDisabled(item.children)
      })
    },
    //部门树-选择
    getCheckedKeys() {
      let oldDepartName = this.$refs.tree.$refs.tree.getCheckedNodes();
      let arr = [];
      oldDepartName.forEach((item, index) => {
        if (item.type == 5) arr.push(item);
      });
      let idArr = [];
      arr.forEach((item) => {
        idArr.push(item.id);
      });
      this.checkedDepartName = this.changeTree(arr).join(",");
      this.popList.sysDeptIds = idArr;
    },
    changeTree(val) {
      let arr = [];
      if (val && val.length !== 0) {
        val.forEach((item) => {
          let obj = {};
          obj.name = item.name;
          if (item.children && item.children.length >= 1) {
            obj.children = this.changeTree(item.children);
          }
          arr.push(obj.name);
        });
      }

      return arr;
    },
    //分页
    currentChange(currentPage) {
      this.currentPage = currentPage * this.pageSize - this.pageSize;
      this.filterUser(currentPage * this.pageSize - this.pageSize);
    },
    //表格行新增
    handleAdd() {
      this.popTitle = "新增";
      this.isEditor = false;
      Object.keys(this.popList).forEach((v) => {
        // debugger
        this.popList[v] = "";
      });
      this.checkedDepartName = "";
      this.popupActivoAdd = true;
      this.$validator.reset();
      this.handleRemove();
      this.getDepartData();
      this.clearTree();
    },
    addUser() {
      // debugger
      this.popupActivoAdd = false;
      // this.popList.icon = JSON.stringify(this.popList.icon);
      console.log(this.popList.icon);
      if (this.popTitle == "编辑") {
        this.$api.accessControl
          .editUser(this.popList)
          .then((res) => {
            console.log(res, "//;;;;");
            if (res.data.success) {
              this.filterUser(this.currentPage);
              this.$emit("reloadTree");
              this.$vs.notify({
                text: "保存成功",
                color: "success",
              });
            } else {
              if (
                res.data.message ==
                "当前手机号已经被其他用户使用,请选用其他号码"
              ) {
                this.$vs.notify({
                  text: `${res.data.message}`,
                  color: "danger",
                });
              } else {
                this.$vs.notify({
                  text: `保存失败`,
                  color: "danger",
                });
              }
            }
          })
          .catch(() => {});
      } else {
        this.$api.accessControl
          .testUserName({ username: this.popList.username })
          .then((res) => {
            console.log(res, "////....");
            if (!res.data.success) {
              this.$vs.notify({
                text: `${res.data.message}`,
                color: "danger",
              });
            } else {
              this.$api.accessControl
                .testPhone({ phone: this.popList.mobile })
                .then((res) => {
                  if (!res.data.success) {
                    this.$vs.notify({
                      text: `${res.data.message}`,
                      color: "danger",
                    });
                  } else {
                    delete this.popList.userId;
                    this.$api.accessControl
                      .addUser(this.popList)
                      .then((res) => {
                        if (res.data.success) {
                          this.clearTree();
                          this.filterUser(this.currentPage);
                          this.$emit("reloadTree");
                          this.$vs.notify({
                            text: "保存成功",
                            color: "success",
                          });
                        } else {
                          this.$vs.notify({
                            text: `保存失败`,
                            color: "danger",
                          });
                        }
                      })
                      .catch(() => {});
                  }
                });
            }
          });
      }
    },
    //清空资源树
    clearTree() {
      this.$refs.tree.$refs.tree.setCheckedKeys([]);
    },
    //表格行编辑
    handleEdit(index, row) {
      // debugger
      console.log(row, "===");
      this.popList.sysDeptIds = [];
      this.checkedDepartName = "";
      let oldDepartName = [];
      if (row.sysDepts) {
        row.sysDepts.forEach((v) => {
          this.popList.sysDeptIds.push(v.deptId);
          oldDepartName.push(v.name);
        });
        this.$refs.tree.$refs.tree.setCheckedKeys(this.popList.sysDeptIds);
        this.checkedDepartName = oldDepartName.join(",");
      }
      let _this = this;
      Object.keys(this.popList).forEach(function (v) {
        _this.popList[v] = row[v];
        console.log(v);
      });
      _this.popList["userId"] = row.userId;
      // console.log(JSON.parse(row.icon)[0].fileId)
      if (row.icon && JSON.parse(row.icon).length) {
        let fileId = JSON.parse(row.icon)[0].fileId;
        this.file = `${this.uploadUrl}/file/${fileId}`;
      } else {
        this.file = "";
      }
      this.popTitle = "编辑";
      this.popupActivoAdd = true;
      this.isEditor = true;
    },
    //表格行设置密码
    handleEditPassword(index, row) {
      this.popPasswordlist.oldPassword = "";
      this.popPasswordlist.newPassword = "";
      this.popPasswordlist.confirmNewPassword = "";
      this.popupActivoPassword = true;
      this.selectRowId = row.userId;
      this.$validator.reset();
    },
    //表格行删除
    handleDelete(delIndex, delRow) {
      this.popupActivoDel = true;
      this.selectRowId = delRow.userId;
    },
    delData() {
      this.$api.accessControl
        .delUser(this.selectRowId)
        .then((res) => {
          if (res.data.success) {
            this.$vs.notify({ text: "删除成功", color: "danger" });
            this.filterUser(this.currentPage);
          } else {
            this.$vs.notify({ text: "删除失败", color: "danger" });
          }
        })
        .catch(() => {});
      this.popupActivoDel = false;
    },
    //用户筛选
    filterUser(startPage) {
      let params = {
        start: startPage || 0,
        length: this.pageSize,
        realName: this.searchList.realname,
      };
      this.$api.accessControl
        .searchUser(params)
        .then((res) => {
          this.tableData = res.data.data;
          this.recordsTotal = res.data.recordsTotal;
        })
        .catch(() => {});
    },
    //用户冻结
    handleSwitch(index, row) {
      if (row.status == 1) {
        this.$api.accessControl
          .userStatusFrozen({ userId: row.userId })
          .then((res) => {
            if (res.data.success) {
              this.$vs.notify({ text: "停止成功", color: "success" });
              this.filterUser(this.currentPage);
            } else {
              this.$vs.notify({ text: "停止失败", color: "danger" });
            }
          })
          .catch(() => {});
      } else {
        // userStatusEnable
        this.$api.accessControl
          .userStatusEnable({ userId: row.userId })
          .then((res) => {
            if (res.data.success) {
              this.$vs.notify({ text: "启用成功", color: "success" });
              this.filterUser(this.currentPage);
            } else {
              this.$vs.notify({ text: "启用失败", color: "danger" });
            }
          })
          .catch(() => {});
      }
    },
    //用户设置密码
    confirmPassword() {
      if (
        this.popPasswordlist.newPassword !=
        this.popPasswordlist.confirmNewPassword
      ) {
        this.$vs.notify({ text: "两次输入密码不一致", color: "danger" });
        return;
      }
      let params = {
        userId: this.selectRowId,
        oldPassword: md5(this.popPasswordlist.oldPassword),
        newPassword: md5(this.popPasswordlist.confirmNewPassword),
      };

      this.$api.accessControl
        .userSetPassWord(params)
        .then((res) => {
          if (res.data.success) {
            this.$emit("reloadTree");
            this.$vs.notify({
              text: "密码修改成功",
              color: "success",
            });
            this.popupActivoPassword = false;
            this.popPasswordlist.oldPassword = "";
            this.popPasswordlist.newPassword = "";
            this.popPasswordlist.confirmNewPassword = "";
          } else {
            this.$vs.notify({
              text: `${res.data.message}`,
              color: "danger",
            });
          }
        })
        .catch(() => {});
    },
    //关闭设置密码弹窗
    closeConfirmPassword() {
      this.popupActivoPassword = false;
    },
    //部门选择框
    switchDepart() {
      this.chooseDepart = !this.chooseDepart;
    },
  },
  watch: {
    popupActivoAdd() {
      this.popupActivoAdd ? "" : (this.chooseDepart = true);
    },
    image(value) {
      this.file = value;
    },
    clearList() {
      this.file = "";
    },
    file(value) {
      const list = value;
      this.$emit("update:image", list);
    },
  },
  computed: {
    handleIsValidate() {
      return (
        !this.errorBags.any() &&
        this.popList.realname != "" &&
        this.popList.username != "" &&
        this.popList.mobile != "" &&
        this.checkedDepartName != "" 
        // && this.popList.icon != "" 
      );
    },
    handleEditorPassword() {
      return (
        !this.errorBags.any() &&
        this.popPasswordlist.oldPassword != "" &&
        this.popPasswordlist.newPassword != "" &&
        this.popPasswordlist.confirmNewPassword != ""
      );
    },
    hideShow() {
      //当图片多于一张的时候，就隐藏上传框
      return this.file === "" ? false : true;
    },
  },
  components: {
    VuePerfectScrollbar,
    TreeComponent,
  },
  created() {
    this.filterUser();
  },
  mounted() {
    this.getDepartData();
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/baseColor.scss";
@import "~@/assets/fonts/other-icon/iconfont.css";

/deep/.vs-input--input.normal {
  font-size: 11.9px;
}
.userSearchTop {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .vs-component.vs-con-input-label.vs-input {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 22rem;
    /deep/ .vs-input--label {
      margin-right: 0.8rem;
    }
    /deep/ .vs-inputx.vs-input--input.hasIcon.icon-after-input {
      padding: 0.7rem 1rem !important;
    }
  }
}
.userSearch {
  position: relative;
}
.addUserBtn {
  color: #fff;
  background: $mainColor;
}
.saveAddData {
  float: right;
}
.addPopcontent {
  display: flex;
  justify-content: space-between;
  > div {
    width: 50%;
    .con-select,
    .vs-input {
      width: 98% !important;
      margin: 0 auto;
    }
  }
}
.editPassword {
  .con-select,
  .vs-input {
    width: 100% !important;
  }
}

@media screen and (max-width: 1920px) {
  .departContainer {
    // border-radius: 0 2% 2% 0;
    width: 20%;
    position: absolute;
    right: calc(27% - 245px);
    top: 30%;
    height: 48.5%;
    z-index: 1;
    .pl-3 {
      margin-top: 15px;
      // margin-left:20px;
    }
  }
}
// @media screen and (max-width: 1366px) {
//   .departContainer {
//     border-radius: 0 2% 2% 0;
//     width: 250px;
//     position: absolute;
//     right: calc(30% - 280px);
//     top: 20%;
//     height: 65%;
//     z-index: 1;
//   }
// }
/deep/.el-input__inner:focus {
  border-color: $mainColor;
}
/deep/.el-input__inner {
  // background-color: #dcdfe6;
}
/deep/.el-input-group__append,
.el-input-group__prepend {
  background-color: transparent;
  border-color: transparent;
}
.chooseBtn {
  padding-top: 1.1rem;
  font-size: 0.85rem;
  color: #fff !important;
  background-color: $mainColor;
}
.closeBtn {
  padding-top: 1.1rem;
  font-size: 0.85rem;
  color: #fff !important;
  background-color: #f56c6c !important;
}
.scroll-area {
  height: calc(var(--vh, 1vh) * 100 - 27.9rem);
  /deep/ .el-icon-folder-opened:before {
    content: "" !important;
  }
}
.el-upload-list--picture-card .el-upload-list__item,
/deep/.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.el-icon-upload-success.el-icon-check {
  position: relative;
  top: -35px;
}
.email {
  display: block;
}
/deep/ i.othericon {
  color: $mainColor;
  font-size: 18px;
}
</style>
